package com.moon.back.service.impl.detemination;

import com.hankcs.hanlp.corpus.dependency.CoNll.CoNLLSentence;
import com.hankcs.hanlp.corpus.dependency.CoNll.CoNLLWord;
import com.hankcs.hanlp.dependency.IDependencyParser;
import com.hankcs.hanlp.dependency.nnparser.NeuralNetworkDependencyParser;
import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.tokenizer.StandardTokenizer;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分析
 */
public class FileOperationExecutor {

    // 依存分析器
    private static final IDependencyParser parser = new NeuralNetworkDependencyParser();
    
    // 支持的操作类型枚举
    enum OperationType { DELETE, MOVE, RENAME, COPY }

    // 操作指令数据结构
    static class FileOperation {
        OperationType type;
        Path source;
        Path target; // 用于MOVE/COPY/RENAME
        Map<String, Object> conditions = new HashMap<>();
    }

    public static void main(String[] args) throws Exception {
        String command = "将Downloads目录下包含'报告'且修改时间超过30天的PDF文件移动到Archive目录";
        List<FileOperation> operations = parseCommand(command);
        executeOperations(operations);
    }

    // 核心解析方法
    private static List<FileOperation> parseCommand(String text) {
        List<Term> terms = StandardTokenizer.segment(text);
        CoNLLSentence sentence = parser.parse(terms);
        
        // 解析操作类型
        OperationType opType = parseOperationType(sentence);
        
        // 解析条件参数
        Map<String, Object> conditions = parseConditions(sentence);
        
        // 解析路径参数
        Path sourcePath = parsePath(sentence, "源路径");
        Path targetPath = parsePath(sentence, "目标路径");

        // 构建操作指令
        FileOperation op = new FileOperation();
        op.type = opType;
        op.source = sourcePath;
        op.target = targetPath;
        op.conditions.putAll(conditions);

        return Collections.singletonList(op);
    }

    // 解析操作类型（示例逻辑）
    private static OperationType parseOperationType(CoNLLSentence sentence) {
        for (CoNLLWord word : sentence.getWordArray()) {
            switch (word.LEMMA) {
                case "删除": return OperationType.DELETE;
                case "移动": return OperationType.MOVE;
                case "重命名": return OperationType.RENAME;
                case "复制": return OperationType.COPY;
            }
        }
        return OperationType.DELETE; // 默认
    }

    // 解析条件参数
    private static Map<String, Object> parseConditions(CoNLLSentence sentence) {
        Map<String, Object> conditions = new HashMap<>();
        for (CoNLLWord word : sentence.getWordArray()) {
            // 文件名条件
            if (word.DEPREL.contains("内容")) {
                conditions.put("fileNameContains", word.LEMMA);
            }
            // 文件类型条件
            if ("文件类型".equals(word.DEPREL)) {
                conditions.put("fileType", word.LEMMA.replace("文件", ""));
            }
            // 时间条件
            if (word.DEPREL.contains("时间")) {
                conditions.put("modifiedDays", parseDays(word.LEMMA));
            }
        }
        return conditions;
    }

    // 解析路径参数（简化示例）
    private static Path parsePath(CoNLLSentence sentence, String type) {
        for (CoNLLWord word : sentence.getWordArray()) {
            if (word.DEPREL.contains("路径") && word.LEMMA.contains(type)) {
                return Paths.get(word.LEMMA.replace(type, ""));
            }
        }
        return Paths.get(System.getProperty("user.home")); // 默认路径
    }

    // 执行文件操作
    private static void executeOperations(List<FileOperation> operations) throws IOException {
        for (FileOperation op : operations) {
            Files.walkFileTree(op.source, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                    try {
                        if (matchConditions(file, op.conditions)) {
                            performAction(file, op);
                        }
                    } catch (IOException e) {
                        System.err.println("操作失败: " + file + " - " + e.getMessage());
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    }

    // 条件匹配逻辑
    private static boolean matchConditions(Path file, Map<String, Object> conditions) throws IOException {
        // 文件名包含
        if (conditions.containsKey("fileNameContains")) {
            String keyword = (String) conditions.get("fileNameContains");
            if (!file.getFileName().toString().contains(keyword)) return false;
        }

        // 文件类型过滤
        if (conditions.containsKey("fileType")) {
            String ext = ((String) conditions.get("fileType")).toLowerCase();
            if (!file.toString().endsWith("." + ext)) return false;
        }

        // 修改时间过滤
        if (conditions.containsKey("modifiedDays")) {
            long days = (Long) conditions.get("modifiedDays");
            LocalDate cutoff = LocalDate.now().minusDays(days);
            LocalDate fileDate = Files.getLastModifiedTime(file).toInstant()
                    .atZone(ZoneId.systemDefault()).toLocalDate();
            if (!fileDate.isBefore(cutoff)) return false;
        }

        return true;
    }

    // 执行具体操作
    private static void performAction(Path file, FileOperation op) throws IOException {
        switch (op.type) {
            case DELETE:
                Files.deleteIfExists(file);
                System.out.println("删除文件: " + file);
                break;
            case MOVE:
                Path target = op.target.resolve(file.getFileName());
                Files.move(file, target, StandardCopyOption.REPLACE_EXISTING);
                System.out.println("移动文件: " + file + " → " + target);
                break;
            case RENAME:
                String newName = generateNewName(file, op.conditions);
                Path renamed = file.resolveSibling(newName);
                Files.move(file, renamed);
                System.out.println("重命名: " + file + " → " + renamed);
                break;
            case COPY:
                Path copied = op.target.resolve(file.getFileName());
                Files.copy(file, copied);
                break;
        }
    }

    // 生成新文件名（示例：添加日期后缀）
    private static String generateNewName(Path file, Map<String, Object> conditions) {
        String original = file.getFileName().toString();
        String dateSuffix = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
        return original.replaceFirst("([^.]++)$", "$1_" + dateSuffix);
    }

    // 工具方法：从文本解析天数
    private static long parseDays(String text) {
        return Long.parseLong(text.replaceAll("[^0-9]", ""));
    }
}